<?php
namespace WPSCS_COMPONENTS_PLUGIN;

class Wpscs_componentt_class {
    static $instance;

    public function __construct() {
        if(is_admin()) add_action( 'admin_menu', [ $this, 'admin_menu' ] );
    }

    /**
     * Register our menu page
     *
     * @return void
     */
    public function admin_menu() {
        global $submenu;

        $capability = 'manage_options';
        $slug       = 'wpcsc-components-center';

        $hook = add_menu_page( __( '组件管理中心', 'textdomain' ), __( '组件管理中心', 'textdomain' ), $capability, $slug, [ $this, 'plugin_page' ]);

        if ( current_user_can( $capability ) ) {
            $submenu[ $slug ][] = array( __( '组件管理', 'textdomain' ), $capability, 'admin.php?page=' . $slug . '#/main' );
        }

        add_action( 'load-' . $hook, [ $this, 'init_hooks'] );
    }

    /**
     * Initialize our hooks for the admin page
     *
     * @return void
     */
    public function init_hooks() {
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
    }

    /**
     * Load scripts and styles for the app
     *
     * @return void
     */
    public function enqueue_scripts() {
        wp_enqueue_script( 'wpscs-baseplugin-tailwind' );
        wp_enqueue_script( 'wpscs-baseplugin-vendor' );
        wp_enqueue_script( 'wpscs-baseplugin-frontend' );
        wp_enqueue_style( 'wpscs-baseplugin-style' );
    }

    /**
     * Render our admin page
     *
     * @return void
     */
    public function plugin_page() {
        echo '<div class="wrap"><div id="wpscs-admin-app"></div></div>';
        echo "<script>(function(Vue){document.addEventListener('DOMContentLoaded', function(){const mountPoint=document.getElementById('wpscs-admin-app');if(!mountPoint) return;const app = Vue.createApp(window.wpcc_components_admin['main']);const componentInstance = app.mount(mountPoint);const componentRoot = componentInstance.\$el;mountPoint.parentNode.replaceChild(componentRoot, mountPoint);})})(\$wpcc_vue);</script>";
    }

    public static function init() {
        if ( ! Wpscs_componentt_class::$instance ) {
            Wpscs_componentt_class::$instance = new Wpscs_componentt_class();
        }
        return Wpscs_componentt_class::$instance;
    }
}

Wpscs_componentt_class::init();